//
//  ZYNewListCommonCourseController.m
//  优学荟管理系统
//
//  Created by edz on 2018/1/9.
//  Copyright © 2018年 星道三好. All rights reserved.
//
#import "SAWAllCorrectHomework.h"
#import "ZYNewListCommonCourseController.h"
#import "ZYNewListCommonCourseModel.h"
#import "ZYNewListCommonCourseCell.h"
#import "ZYNewListCommonCouseTwoCell.h"
#import "ZYAddStrongCouseController.h"
#define kCell @"cell"
#import "TeacherCourseSelectView.h"
#import "ZYTeacherAllSuperView.h"
#import "ZYStudentDivisionController.h"
#import "XZSelectedView.h"
#import "HNHandleCourseVC.h"
#import "HNCourseListChartsModel.h"
#import "SQCustomButton.h"
@interface ZYNewListCommonCourseController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,assign) BOOL isTrue;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,strong) UIView *allView;
@property (nonatomic,copy) NSString *iDStr;
@property (nonatomic,strong) UIView *allViews;
@property (nonatomic,strong) UITextField *searchTextField;
@property (nonatomic,strong) UIButton *searchButton;
@property (nonatomic,strong) NSString *sorting;
@property (nonatomic,strong) ZYNewListCommonCourseModel *model;

@end

@implementation ZYNewListCommonCourseController

- (NSMutableArray *)dataSource{
    
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];
    [SVProgressHUD dismiss];
}





- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = ColorRGB(245, 245, 245);
    
    self.sorting = @"0";
    [self setSearchName];
    
    [self setUpSuperView];
    [self setUpRefresh];
    
    UIBarButtonItem *liftItem = [UIBarButtonItem itemWithTargat:self action:@selector(itemAction) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
    
    
    self.navigationItem.leftBarButtonItem =liftItem;
    
    if (!self.IsProgramStudy) {
        UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
        [rightBtn setTitle:@"排序方式" forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [rightBtn addTarget:self action:@selector(rightBarButtonItemAction) forControlEvents:UIControlEventTouchUpInside];
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    }
    
   
}


- (void)rightBarButtonItemAction{
    
    XZSelectedView *view = [[XZSelectedView alloc] initview];
    view.callBack = ^(NSString *index) {
        _sorting = index;
        [self.tableView.mj_header beginRefreshing];
    };
    [self.view addSubview:view];
    
}



- (void)setSearchName{
    
    self.allViews = [[UIView alloc]initWithFrame:CGRectMake(40, 0, kScreenWidth - 180, 30)];
    self.allViews.backgroundColor = ColorRGB(247,245,245);
    self.allViews.layer.cornerRadius = 15;
    self.allViews.clipsToBounds = YES;
    self.navigationItem.titleView = self.allViews;
    
    self.searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, self.allViews.frame.size.width, self.allViews.frame.size.height)];
    self.searchTextField.font = [UIFont systemFontOfSize:13];
    self.searchTextField.textColor = ColorRGB(102, 102, 102);
    self.searchTextField.textAlignment = NSTextAlignmentCenter;
    self.searchTextField.returnKeyType =  UIReturnKeySearch;
    self.searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.searchTextField.delegate = self;
    [self.allViews addSubview:self.searchTextField];
    
    
    self.searchButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.searchButton setImage:[UIImage imageNamed:@"icon_serch_default"] forState:(UIControlStateNormal)];

    [self.searchButton setTitle:@"  搜索课程或老师" forState:(UIControlStateNormal)];
    [self.searchButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    self.searchButton.titleLabel.font = [UIFont systemFontOfSize:13];
    self.searchButton.frame = self.searchTextField.frame;
    [self.allViews addSubview:self.searchButton];
    
    [self.searchButton addTarget:self action:@selector(searchButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.searchTextField addTarget:self action:@selector(searchTextFieldAction:) forControlEvents:(UIControlEventEditingChanged)];
    
    
}


- (void)searchButtonAction:(UIButton *)sender{
    
    
    [self.searchTextField becomeFirstResponder];
    
}

- (void)searchTextFieldAction:(UITextField *)textField{
    
    
    self.searchButton.hidden = textField.text.length;
    
    
    
    
}





- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.searchTextField resignFirstResponder];
    
    [self setNetWork];
    //[self.tableView.mj_header beginRefreshing];
    
    return YES;
}









- (void)itemAction{
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark --- 添加课程的入口
- (void)addButtonAction{
    
    HNHandleCourseVC *VC = [[HNHandleCourseVC alloc] init];
    // 声明我这是添加课程
    VC.type = HNHandleCourseTypeAdd;
    VC.PopOfRefresh = ^ {
        
        
            [self.tableView.mj_header beginRefreshing];
            
    };
     VC.isProgram = self.IsProgramStudy;
    [self.navigationController pushViewController:VC animated:YES];
    
}


#pragma mark --- 上拉加载和下拉刷新方法的实现
- (void)setUpRefresh{
    
    //下拉刷新
    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    //自动更改透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    //结束头部刷新
    [self.tableView.mj_header endRefreshing];
    //结束尾部刷新
    [self.tableView.mj_footer endRefreshing];
    
    
}

/**
 *  上拉加载
 */
- (void)upRefresh{
    
    self.isTrue = NO;
    self.page++;
    [self setNetWork];
    
}
/**
 *  下拉刷新
 */

- (void)downRefresh{
    self.isTrue = YES;
    self.page = 1;
    [self setNetWork];
    
    
}

- (void)setNetWork{
    
    //    http://192.168.0.113:8080/StarShine/ys/yxhUser.do
    NSString *oid = [AccountTool shareAccountTool].currentAccount.oid;
    NSInteger type = 1;
    if (_IsProgramStudy) {
        type = 4;
    }
    NSString *url = [NSString stringWithFormat:@"yxhUser.do?oid=%@&action=getLessonList&pageNumber=%ld&type=%ld&searchName=%@&status=0&parameter=%@",oid,(long)self.page,(long)type,self.searchTextField.text?self.searchTextField.text:@"",self.sorting];
    
    NSString *changeUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
    [NetManager Get:LLBaseURL(changeUrl) Auth:YES Params:nil Success:^(id Obj) {
        
        [SVProgressHUD dismiss];
        NSDictionary *t = [Obj valueForKey:@"t"];
        
        NSArray *arr = [t valueForKey:@"dataList"];
        if ([[Obj valueForKey:@"code"] integerValue] == 1000 ) {
            if (self.isTrue == YES) {
                
                [self.dataSource removeAllObjects];
                
            }
            
            
            
            if (arr != nil && ![arr isKindOfClass:[NSNull class]] ){
                
                
                for (NSDictionary *dict in arr) {
                    
                    ZYNewListCommonCourseModel *model = [ZYNewListCommonCourseModel new];
                    
                    [model setValuesForKeysWithDictionary:dict];
                    model.ID = [dict valueForKey:@"id"];
                    [self.dataSource addObject:model];
                    
                }
                
                
                
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
               
                
                
                
                
            }else{
                
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
                
                
            }
            
            
            
            
            
            
        }
        
        else{
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
            
        }
        
        
        
        
    } Fail:^(NSError *Error) {
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
    
    
    
}






- (void)setUpSuperView{
    
    
   
    
    if(!self.IsProgramStudy)
    {
        self.allView = [[UIView alloc]initWithFrame:CGRectMake(kScreenWidth *26/750,kScreenHeight *26/1334, kScreenWidth - (kScreenWidth *26/750)*2, kScreenHeight *88/1334)];
        self.allView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.allView];
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake(kScreenWidth *30/750, 0, self.allView.frame.size.width, self.allView.frame.size.height);
        [button setImage:[UIImage imageNamed:@"icon_add_class_default"] forState:(UIControlStateNormal)];
        [button setTitle:@"  添加课程" forState:(UIControlStateNormal)];
        [button setTitleColor:ColorRGB(78, 211, 167) forState:(UIControlStateNormal)];
        [self.allView addSubview:button];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button addTarget:self action:@selector(addButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
        
        UIButton *pushButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        pushButton.frame = CGRectMake(self.allView.frame.size.width - 50, 0, 50, 50);
        [pushButton setImage:[UIImage imageNamed:@"icon_back_default"] forState:(UIControlStateNormal)];
        [self.allView addSubview:pushButton];
    }
   
   
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(self.allView.frame.origin.x, self.IsProgramStudy ? 0 : self.allView.frame.origin.y + self.allView.frame.size.height, kScreenWidth - (self.allView.frame.origin.x)*2, kScreenHeight - 64 - kScreenHeight *88/1334) style:(UITableViewStyleGrouped)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerClass:[ZYNewListCommonCourseCell class] forCellReuseIdentifier:kCell];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(-54, 0, 0, 0);
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight *26/1334)];
    lineView.backgroundColor = ColorRGB(245, 245, 245);
    self.tableView.tableHeaderView = lineView;
    
    
    
    
    
    
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    ZYNewListCommonCourseModel *model = self.dataSource[section];
    
    return model.elementCount.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZYNewListCommonCourseCell *cell = [tableView dequeueReusableCellWithIdentifier:kCell forIndexPath:indexPath];
    
    if (self.dataSource.count>0) {
        ZYNewListCommonCourseModel *model = self.dataSource[indexPath.section];
        ZYNewListCommonCourseSubOneModel *moodelTow = model.elementCount[indexPath.row];
        [cell assignByZYNewListCommonCourseSubOneModel:moodelTow];
    }
   
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    
   
    
    
    
    
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    ZYNewListCommonCourseModel *model = self.dataSource[section];
    
    if (model.elementCount.count > 0) {
        
        return 100  + 50 *model.teachers.count;
    }else{
        
        return 60 + 50 *model.teachers.count;
    }
    
    
    
    
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    ZYNewListCommonCourseModel *model = self.dataSource[section];
    
    
    UIView *vv = [UIView new];
    vv.backgroundColor = [UIColor whiteColor];
    UIView *oneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - (kScreenWidth *26/750)*2, 40)];
    [vv addSubview:oneView];
    
    
    UIButton *upDownButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    upDownButton.frame = CGRectMake(0, 0,40, oneView.frame.size.height);
    [oneView addSubview:upDownButton];
    
    
    
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(upDownButton.frame.origin.x + upDownButton.frame.size.width, upDownButton.frame.origin.y, oneView.frame.size.width - (upDownButton.frame.origin.x + upDownButton.frame.size.width)*2, upDownButton.frame.size.height)];
    nameLabel.text = [NSString stringWithFormat:@"%@",model.name];
    nameLabel.font = [UIFont systemFontOfSize:15];
    nameLabel.textColor = ColorRGB(51, 51, 51);
    [oneView addSubview:nameLabel];
    
    
    UIButton *pushButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    pushButton.frame = CGRectMake(oneView.frame.size.width - 50, nameLabel.frame.origin.y, 50, 50);
    [pushButton setImage:[UIImage imageNamed:@"icon_back_default"] forState:(UIControlStateNormal)];
    pushButton.tag = 1000 + section;
    [oneView addSubview:pushButton];
    
    UIImageView * lineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40,oneView.frame.size.width, 2)];
    lineView.image = [UIImage imageNamed:@"seg_shangjia_default"];
    [vv addSubview:lineView];
    
    
    
    
    
    
    ZYTeacherAllSuperView *zyTeacher = [[ZYTeacherAllSuperView alloc]initWithFrame:CGRectMake(0, lineView.frame.origin.y + lineView.frame.size.height, oneView.frame.size.width, 50 *model.teachers.count) dataSource:model.teachers];
    
    //学生分班
    zyTeacher.pushsBlock = ^(NSString *ID) {
        
        ZYStudentDivisionController *VC = [[ZYStudentDivisionController alloc] init];
        VC.lessonId = model.ID;
        VC.teacherUid  = ID;
        [self.navigationController pushViewController:VC animated:YES];
        
        
        
    };
    
    
    
    
    
    [vv addSubview:zyTeacher];
    
    UIImageView * lineViewThree = [[UIImageView alloc] initWithFrame:CGRectMake(0,zyTeacher.frame.origin.y + zyTeacher.frame.size.height,oneView.frame.size.width, 2)];
    lineViewThree.image = [UIImage imageNamed:@"seg_shangjia_default"];
    [vv addSubview:lineViewThree];
    
    
    if (model.elementCount.count > 0) {
        
        UILabel *goodEvaluationLabel = [[UILabel alloc]initWithFrame:CGRectMake(lineViewThree.frame.origin.x, lineViewThree.frame.origin.y + lineViewThree.frame.size.height + 8, lineViewThree.frame.size.width, 20)];
        
        goodEvaluationLabel.text =@"三好评价得优统计表";
        goodEvaluationLabel.textAlignment = NSTextAlignmentCenter;
        goodEvaluationLabel.textColor = ColorRGB(153, 153, 153);
        [vv addSubview:goodEvaluationLabel];
        
        UILabel *unit = [[UILabel alloc] init];
        unit.frame = CGRectMake(0, 0, 100, goodEvaluationLabel.frame.size.height);
        unit.center = CGPointMake(kScreenWidth - 50, goodEvaluationLabel.center.y);
        unit.text = @"得优个数(个)";
        unit.font = [UIFont systemFontOfSize:12.f];
        unit.textColor = ColorRGB(153, 153, 153);
        [vv addSubview:unit];
        
    }
 
    
    
    
    
    
    
    
    
    
    
    [upDownButton setImage:[UIImage imageNamed:@"bg_image_shangjia_default"] forState:(UIControlStateNormal)];
    
    
    
    
    
    
    
    [pushButton addTarget:self action:@selector(pushTwoButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    
    
    
    return vv;
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    
    return 60;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    ZYNewListCommonCourseModel *model = self.dataSource[section];
    self.model = model;
    UIView *vv = [UIView new];
    vv.backgroundColor = [UIColor whiteColor];
    
//    //-------折叠按钮
//    UIButton *btn = [[UIButton alloc]init];
//    btn.backgroundColor=[UIColor orangeColor];
//    [vv addSubview:btn];
//    btn.frame = CGRectMake((kScreenWidth - (kScreenWidth *26/750)*2)/2 - 60, 5, 120, 40);
//    //-------折叠按钮
    
    if (!self.IsProgramStudy) {
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake((kScreenWidth - 220)/3, 0, 100, 30);
        [button setBackgroundImage:[UIImage imageNamed:@"btn_competition_default"] forState:(UIControlStateNormal)];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitle:@"开设加强课" forState:(UIControlStateNormal)];
        [button setTitleColor:ColorRGB(255, 254, 254) forState:(UIControlStateNormal)];
        [vv addSubview:button];
        
        button.tag = section + 1002;
        [button addTarget:self action:@selector(openStongbuttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        UIButton *button1 = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button1.frame = CGRectMake((kScreenWidth - 220)/3*2+100, 0, 100, 30);
        [button1 setBackgroundImage:[UIImage imageNamed:@"btn_competition_default"] forState:(UIControlStateNormal)];
        button1.titleLabel.font = [UIFont systemFontOfSize:15];
        [button1 setTitle:@"错题集中营" forState:(UIControlStateNormal)];
        [button1 setTitleColor:ColorRGB(255, 254, 254) forState:(UIControlStateNormal)];
         button1.tag = section + 1666;
        [button1 addTarget:self action:@selector(knowLedgePush:) forControlEvents:(UIControlEventTouchUpInside)];
        [vv addSubview:button1];
        
        UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, button.frame.origin.y + button.frame.size.height + 5, kScreenWidth, 10)];
        lineLabel.backgroundColor = ColorRGB(245, 245, 245);
        [vv addSubview:lineLabel];
        
     
    }
 
    return vv;
    
}


-(void)knowLedgePush:(UIButton *)sender
{
     self.model = self.dataSource[sender.tag -1666];
    SAWAllCorrectHomework *vc= [SAWAllCorrectHomework new];
    vc.ID = self.model.ID;
     [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --- 开设加强课方法的实现
- (void)openStongbuttonAction:(UIButton *)sender{
    
    self.model = self.dataSource[sender.tag - 1002];
    // 得三好要素得优统计表数据
    NSMutableArray <HNCourseListChartsModel *>*arr = [NSMutableArray array];
    [self.model.elementCount enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [arr addObject:[[HNCourseListChartsModel alloc] init_ValuForKeyWithDict:obj]];
    }];
    
    
    HNHandleCourseVC *VC = [[HNHandleCourseVC alloc] init];
    // 声明我这是添加加强课
    VC.type = HNHandleCourseTypeStrongAdd;
    // 对应的课程
    VC.Id = @([self.model.ID integerValue]);
    // 加强课要素
    VC.strongDatas = [arr copy];
    VC.PopOfRefresh = ^{
        
        [self.tableView.mj_header beginRefreshing];
    };
    VC.isProgram = self.IsProgramStudy;
    [self.navigationController pushViewController:VC animated:YES];
    
    
}


#pragma mark --- 编辑方法的实现
- (void)pushTwoButtonAction:(UIButton *)sender{
    
    ZYNewListCommonCourseModel *model = self.dataSource[sender.tag -1000];
    HNHandleCourseVC *VC = [[HNHandleCourseVC alloc] init];
    // 声明我这是修改课程
    VC.type = HNHandleCourseTypeEdit;
    // 对应的课程
    VC.PopOfRefresh = ^{
        
        [self.tableView.mj_header beginRefreshing];
    };
    VC.Id = @([model.ID integerValue]);
     VC.isProgram = self.IsProgramStudy;
    [self.navigationController pushViewController:VC animated:YES];
    
}





@end
